<template>
  <a-modal
    class="z-modal"
    width="60%"
    v-model:open="show_calc"
    :title="handleTitle"
    @ok="showModalCon"
    @cancel="showModalCancel"
  >
    <div class="flex-column">
      <div>
        <a-tabs v-model:activeKey="tabsKey">
          <a-tab-pane
            :key="item.value"
            :tab="item.label"
            v-for="(item, index) in type_calc"
          ></a-tab-pane>
        </a-tabs>
      </div>
      <div style="height: 400px; overflow-y: auto">
        <div
          v-global-loading="orgLoading"
          style="min-height: 100px"
          v-show="tabsKey === 1"
        >
          <a-tree
            checkable
            v-if="orgArr && orgArr.length"
            v-model:checkedKeys="orgSelect_calc"
            default-expand-all
            :tree-data="orgArr"
            @check="check"
            :fieldNames="{children: 'children', title: 'title', key: 'id'}"
          >
            <template #title="item">
              {{ item.title }}
            </template>
          </a-tree>
        </div>
        <div v-show="tabsKey === 2" style="height: 100%">
          <div class="flex-row" style="height: 100%">
            <div class="flex1" style="height: 100%">
              <a-tree
                v-if="orgArr && orgArr.length"
                v-model:selectedKeys="orgSelectForUser"
                default-expand-all
                :tree-data="orgArr"
                @select="treeSelect"
              >
                <template #title="item">
                  {{ item.title }}
                </template>
              </a-tree>
            </div>
            <div class="flex1" style="overflow-y: auto; height: 100%">
              <a-table
                :row-selection="{
                  selectedRowKeys: userSelect_calc,
                  onChange: userSelectChange,
                  onSelectInvert: userSelectChangeNot
                }"
                size="small"
                row-key="id"
                :loading="tableLoading"
                :dataSource="tableData"
                :columns="columns"
                bordered
                :pagination="false"
              >
              </a-table>
            </div>
          </div>
        </div>
        <div v-show="tabsKey === 3">
          <a-table
            :row-selection="{
              selectedRowKeys: roleSelect_calc,
              onChange: roleSelectChange
            }"
            size="small"
            row-key="id"
            :loading="tableLoadingForRole"
            :dataSource="tableDataForRole"
            :columns="columnsForRole"
            bordered
            :pagination="false"
          >
          </a-table>
        </div>
      </div>
      <div class="mt-10">
        <!--        <Pagination :page-set="pageSet" :load-pagination="loadPagination"-->
        <!--                    v-show="tabsKey === 2"></Pagination>-->
        <!--        <Pagination :page-set="pageSetForRole" :load-pagination="loadPaginationForRole"-->
        <!--                    v-show="tabsKey === 3"></Pagination>-->
        <div class="areadySelect mt-10">
          <div
            class="flex-row-ycenter label"
            v-for="(item, index) in orgArrAready"
            :key="index"
          >
            <div>{{ item.title }}</div>
            <div class="close" @click="deleteTarget(1, item, index)">
              <component
                class="fs-20 c-999 pointer"
                is="close-circle-outlined"
              ></component>
            </div>
          </div>
          <div
            class="flex-row-ycenter label"
            v-for="(item, index) in userArrAready"
            :key="index"
          >
            <div>{{ item.name }}</div>
            <div class="close" @click="deleteTarget(2, item, index)">
              <component
                class="fs-20 c-999 pointer"
                is="close-circle-outlined"
              ></component>
            </div>
          </div>
          <div
            class="flex-row-ycenter label"
            v-for="(item, index) in roleArrAready"
            :key="index"
          >
            <div>{{ item.name }}</div>
            <div class="close" @click="deleteTarget(3, item, index)">
              <component
                class="fs-20 c-999 pointer"
                is="close-circle-outlined"
              ></component>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import {computed, ref} from "vue";
import {orgTree, userPage} from "@/api/configCenter/auth/people";
import {rolePage} from "@/api/configCenter/auth/role";
import {deepClone} from "@/utils/common";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  //类型[1:部门,2:用户,3:角色]
  type: {
    type: Array,
    default: [1, 2, 3]
  },
  //用户id集合
  userSelect: {
    type: Array,
    default: []
  },
  //角色id集合
  roleSelect: {
    type: Array,
    default: []
  },
  //机构id集合
  orgSelect: {
    type: Array,
    default: []
  }
});
const emits = defineEmits([
  "update:show",
  "ok",
  "update:userSelect",
  "update:roleSelect",
  "update:orgSelect"
]);
const show_calc = computed({
  get() {
    return props.show;
  },
  set(value) {
    emits("update:show", value);
  }
});
const tabsKey = ref<number>(0);
const type_calc = computed(() => {
  let arr = [
    {
      value: 1,
      label: "部门"
    },
    {
      value: 2,
      label: "人员"
    },
    {
      value: 3,
      label: "角色"
    }
  ];
  let newArr: any = arr.filter((item) => props.type.includes(item.value));
  if (tabsKey.value === 0) {
    tabsKey.value = newArr[0].value;
  }
  return newArr;
});
const pageSet = ref({
  pageNo: 1,
  pageSize: 1000,
  total: 0,
  "sysEmpParam.orgId": null
});
const pageSetForRole = ref({
  pageNo: 1,
  pageSize: 1000,
  total: 0
});
const tableData = ref([]); //人员数据
const tableDataForRole = ref([]); //角色数据
const tableLoading = ref(false);
const tableLoadingForRole = ref(false);
const showModal = ref(false);
const handleTitle = ref("选择人员");
const orgArrAready = ref([]);
const userArrAready = ref([]);
const roleArrAready = ref([]);

const orgSelect_calc = computed({
  get() {
    return props.orgSelect;
  },
  set(value) {
    emits("update:orgSelect", value);
  }
});

const check = (checkedKeys, e) => {
  orgArrAready.value = e.checkedNodes;
};

const userSelect_calc = computed({
  get() {
    return props.userSelect;
  },
  set(value) {
    emits("update:userSelect", value);
  }
});
const userSelectChange = (keys: any, rows: any) => {
  userSelect_calc.value = keys;
  userArrAready.value = rows;
};
const userSelectChangeNot = (rows: any) => {};

const roleSelect_calc = computed({
  get() {
    return props.roleSelect;
  },
  set(value) {
    emits("update:roleSelect", value);
  }
});
const roleSelectChange = (keys: any, rows: any) => {
  roleSelect_calc.value = keys;
  roleArrAready.value = rows;
};

let first = true;
const loadPagination = (reset = false) => {
  tableLoading.value = true;
  if (reset) {
    tableData.value = [];
    pageSet.value.pageNo = 1;
  }
  userPage(pageSet.value)
    .then((res) => {
      tableLoading.value = false;
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
      if (props.userSelect.length && first) {
        userArrAready.value = tableData.value.filter((item: any) => {
          return props.userSelect.includes(item.id);
        });
      }
      first = false;
    })
    .catch((err) => {
      tableLoading.value = false;
    });
};
loadPagination();

const loadPaginationForRole = (reset = false) => {
  tableLoadingForRole.value = true;
  if (reset) {
    tableDataForRole.value = [];
    pageSetForRole.value.pageNo = 1;
  }
  rolePage(pageSetForRole.value)
    .then((res) => {
      tableLoadingForRole.value = false;
      tableDataForRole.value = res.data.rows;
      pageSetForRole.value.total = res.data.totalRows;
      if (props.roleSelect.length) {
        roleArrAready.value = tableDataForRole.value.filter((item: any) => {
          return props.roleSelect.includes(item.id);
        });
      }
    })
    .catch((err) => {
      tableLoadingForRole.value = false;
    });
};
loadPaginationForRole();

const deleteTarget = (type: number, info: any, index: number) => {
  if (type === 1) {
    //删除机构
    let i: any = orgSelect_calc.value.findIndex((item) => item == info.id);
    if (i >= 0) orgSelect_calc.value.splice(i, 1);
    orgArrAready.value.splice(index, 1);
  }
  if (type === 2) {
    //删除人员
    let i: any = userSelect_calc.value.findIndex((item) => item == info.id);
    if (i >= 0) userSelect_calc.value.splice(i, 1);
    userArrAready.value.splice(index, 1);
  }
  if (type === 3) {
    //删除角色
    let i: any = roleSelect_calc.value.findIndex((item) => item == info.id);
    if (i >= 0) roleSelect_calc.value.splice(i, 1);
    roleArrAready.value.splice(index, 1);
  }
};

const showModalCon = () => {
  emits("ok", {
    user: userArrAready.value,
    org: orgArrAready.value,
    role: roleArrAready.value
  });
  show_calc.value = false;
};

const showModalCancel = () => {};

const filterArr = (arr, idsArr) => {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (idsArr.includes(arr[i].id)) {
      result.push(arr[i]);
    }
    if (arr[i].children && arr[i].children.length) {
      result.push(...filterArr(arr[i].children, idsArr));
    }
  }
  return result;
};

//机构列表
const orgLoading = ref(false);
const orgArr = ref([]);
const loadOrgTree = () => {
  orgLoading.value = true;
  orgTree()
    .then((res) => {
      orgArr.value = res.data;
      if (props.orgSelect.length) {
        orgArrAready.value = filterArr(deepClone(res.data), props.orgSelect);
      }
      orgLoading.value = false;
    })
    .catch((err) => {
      orgLoading.value = false;
    });
};
loadOrgTree();

const orgSelectForUser = ref([]);
const treeSelect = (selectedKeys, e) => {
  if (e.selected) {
    pageSet.value["sysEmpParam.orgId"] = e.node.id;
  } else {
    pageSet.value["sysEmpParam.orgId"] = null;
  }
  loadPagination(true);
};
const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    align: "center"
  }
];

const columnsForRole = [
  {
    title: "名称",
    dataIndex: "name",
    align: "center"
  }
];

defineExpose({
  showModal
});
</script>

<style lang="less" scoped>
.areadySelect {
  border: 1px solid #dedede;
  padding: 15px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;

  .label {
    padding: 4px 10px;
    background-color: #f1f1f1;
    border-radius: 4px;
    position: relative;
    margin-bottom: 20px;

    & + .label {
      margin-left: 20px;
    }

    .close {
      position: absolute;
      right: -10px;
      top: -10px;
      z-index: 10;
    }
  }
}
</style>
